package com.kaede.hayate.common.base;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kaede.hayate.common.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.HashMap;


public abstract class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	protected String getUserId(HttpServletRequest request) {
		return (String)request.getAttribute("userId");
	}
	
	protected String getUsername(HttpServletRequest request) {
		return (String)request.getAttribute("username");
	}

	public ResponseEntity buildId(Long id){
		HashMap<String, Long> response = new HashMap<>();
		response.put("id", id);
		return ResponseEntity.ok(response);
	}

	protected EntityWrapper buildBaseEntityWrapper(BaseQueryRequest baseQueryRequest){
		EntityWrapper entityWrapper = new EntityWrapper<>();
		if(baseQueryRequest.getId() != null){
			entityWrapper.eq("id", baseQueryRequest.getId());
		}
		if(baseQueryRequest.getCreateBy() != null){
			entityWrapper.eq("create_by", baseQueryRequest.getCreateBy());
		}
		if(baseQueryRequest.getUpdateBy() != null){
			entityWrapper.eq("update_by", baseQueryRequest.getUpdateBy());
		}
		if(baseQueryRequest.getStartCreateDate() != null && baseQueryRequest.getEndCreateDate() != null){
			entityWrapper.between("create_date", baseQueryRequest.getStartCreateDate(), baseQueryRequest.getEndCreateDate());
		}
		if(baseQueryRequest.getStartUpdateDate() != null && baseQueryRequest.getEndUpdateDate() != null){
			entityWrapper.between("update_date", baseQueryRequest.getStartUpdateDate(), baseQueryRequest.getEndUpdateDate());
		}
		return entityWrapper;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		/*binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});*/
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
			/*@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? DateUtils.formatDateTime((Date)value) : "";
			}*/
		});
	}
	
}